package jast;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;

import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.ParseTreeWalker;

import lexer.JavaLexer;
import parser.JavaParser;

public class ProgStub {
	public void stub(String inputFile) throws IOException{
		String inputFileDir = inputFile.substring(0, inputFile.lastIndexOf("\\"));
		File outputDir = new File(inputFileDir+"\\stub");
		if(!outputDir.exists())
			outputDir.mkdirs();
		stub(inputFile, inputFileDir+"\\stub");
	}
	
	public void stub(String inputFile, String ouputDir) throws IOException{
		InputStream is = new FileInputStream(inputFile);
		ANTLRInputStream input = new ANTLRInputStream(is);
		JavaLexer lexer = new JavaLexer(input);
		CommonTokenStream tokens = new CommonTokenStream(lexer);
		JavaParser parser = new JavaParser(tokens);
		ParseTree tree = parser.compilationUnit();
		
		ParseTreeWalker walker = new ParseTreeWalker();
		StubListener listener = new StubListener(tokens);
		walker.walk(listener, tree);
		
		String inputFileName = inputFile.substring(inputFile.lastIndexOf("\\")+1, inputFile.length());
		File outputFile = new File(ouputDir+"\\"+inputFileName);
		if(!outputFile.exists())
			outputFile.createNewFile();
		FileWriter outWriter = new FileWriter(outputFile);
		outWriter.write(listener.rewriter.getText());
		outWriter.close();
		System.out.println(listener.rewriter.getText());
	}
}